package com.ty.zls.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.text.InputType;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.aspsine.swipetoloadlayout.OnLoadMoreListener;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.aspsine.swipetoloadlayout.SwipeToLoadLayout;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.qmuiteam.qmui.widget.grouplist.QMUICommonListItemView;
import com.qmuiteam.qmui.widget.grouplist.QMUIGroupListView;
import com.ty.zls.R;
import com.ty.zls.adapter.RepayAdapter;
import com.ty.zls.bean.Account;
import com.ty.zls.bean.Water;
import com.ty.zls.components.MyReceycleView;
import com.ty.zls.task.BaseTask;
import com.ty.zls.task.PrepayTask;
import com.ty.zls.util.HttpUtil;
import com.ty.zls.util.StringUtils;
import com.ty.zls.util.StrogeUtil;

import org.json.JSONObject;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PrepayActivity extends AppCompatActivity implements View.OnClickListener {

    @ViewInject(R.id.repay_topbar)
    private QMUITopBarLayout repay_topbar;
    @ViewInject(R.id.swipeToLoadLayout)
    private SwipeToLoadLayout swipeToLoadLayout;
    @ViewInject(R.id.swipe_target)
    private MyReceycleView receycleView;
    @ViewInject(R.id.repay_empty)
    private QMUIEmptyView repay_empty;
    @ViewInject(R.id.tv_repay_arreage)
    private TextView tv_repay_arreage;
    @ViewInject(R.id.gl_record_account)
    private QMUIGroupListView gl_record_account;
    @ViewInject(R.id.bt_repay_add)
    private Button bt_repay_add;

    private Map<String,String> request = new HashMap<>();
    private Account account;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        QMUIStatusBarHelper.translucent(this);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_prepay);
        x.view().inject(this);

        initTopbar();
        initPager();
        account = (Account) getIntent().getSerializableExtra("account");
        tv_repay_arreage.setText(account.getArreage());
        bt_repay_add.setOnClickListener(this);
        initGroup();
    }

    private void initGroup() {
        QMUICommonListItemView id = gl_record_account.createItemView(
                ContextCompat.getDrawable(this, R.mipmap.user_id),
                "用户编号",
                account.getId(),
                QMUICommonListItemView.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_NONE);
        QMUICommonListItemView name = gl_record_account.createItemView(
                ContextCompat.getDrawable(this, R.mipmap.user),
                "用户名",
                account.getName(),
                QMUICommonListItemView.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_NONE);
        QMUICommonListItemView area = gl_record_account.createItemView(
                ContextCompat.getDrawable(this, R.mipmap.address),
                "用水地址",
                account.getArea(),
                QMUICommonListItemView.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_NONE);

        int size = QMUIDisplayHelper.dp2px(this, 20);
        QMUIGroupListView.newSection(this)
                .setTitle(null)
                .setDescription(null)
                .setLeftIconSize(size, ViewGroup.LayoutParams.WRAP_CONTENT)
                .addItemView(id, null)
                .addItemView(name, null)
                .addItemView(area, null)
                .addTo(gl_record_account);
    }

    private void initPager() {
        receycleView.setEmptyView(repay_empty);
        receycleView.setLayout(swipeToLoadLayout);

        final List<Water> waters = new ArrayList<>();
        final RepayAdapter adapter = new RepayAdapter(waters, this);
        receycleView.setLayoutManager(new LinearLayoutManager(this));
        receycleView.setAdapter(adapter);
        OnRefreshListener onRefreshListener = new OnRefreshListener() {
            @Override
            public void onRefresh() {
                swipeToLoadLayout.setRefreshing(false);
                adapter.setPageNum(1);
                adapter.setTotal(0);
                adapter.getDatas().clear();
                request.put("pageNum", String.valueOf(1));
                request.put("pageSize", String.valueOf(adapter.getPageSize()));
                request.put("accountId",account.getId());
                PrepayTask task = new PrepayTask(repay_empty,PrepayActivity.this,adapter,swipeToLoadLayout,account.getId());
                task.execute(request);
            }
        };
        swipeToLoadLayout.setOnRefreshListener(onRefreshListener);
        swipeToLoadLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                request.put("pageNum", String.valueOf(adapter.getPageNum()));
                request.put("pageSize", String.valueOf(adapter.getPageSize()));
                request.put("accountId",account.getId());
                PrepayTask task = new PrepayTask(repay_empty,PrepayActivity.this,adapter,swipeToLoadLayout,account.getId());
                task.execute(request);
                swipeToLoadLayout.setLoadingMore(false);
            }
        });
        autoRefresh();
    }

    private void initTopbar() {
        repay_topbar.setTitle("账单记录");
        repay_topbar.setBackgroundColor(getResources().getColor(R.color.app_color_theme_7));
        repay_topbar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PrepayActivity.this.finish();
            }
        });
    }

    public void autoRefresh() {
        swipeToLoadLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeToLoadLayout.setRefreshing(true);
            }
        });
    }


    @Override
    public void onClick(View v) {
        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(this);
        builder.setTitle("缴纳金额")
                .setPlaceholder("在此输入缴纳金额")
                .setDefaultText(account.getArreage())
                .setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL)
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(final QMUIDialog dialog, int index) {
                        final String text = builder.getEditText().getText().toString();
                        if(StringUtils.isEmpty(text)){
                            Toast.makeText(PrepayActivity.this,"请输入缴纳金额",Toast.LENGTH_SHORT).show();
                            return;
                        }
                        Double amount = null;
                        try {
                            amount = Double.valueOf(text);
                        }catch (Exception e){
                            Toast.makeText(PrepayActivity.this,"请输入正确的金额",Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if(amount <= 0){
                            Toast.makeText(PrepayActivity.this,"缴纳金额应大于0",Toast.LENGTH_SHORT).show();
                            return;
                        }
                        Map<String,String> map = new HashMap<>();
                        map.put("accountId",account.getId());
                        map.put("payment",amount.toString());
                        final Double finalAmount = amount;
                        new BaseTask(HttpUtil.PAY_WATER, PrepayActivity.this, new BaseTask.SuccessCallback() {
                            @Override
                            public void excute(JSONObject result) {
                                //跳入打印页
                                account.setPayment(finalAmount);
                                account.setPayee(StrogeUtil.getStringFraomPs(PrepayActivity.this,StrogeUtil.user,"loginName"));
                                account.setPayTime(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
                                Intent intent = new Intent(PrepayActivity.this,PrinterSettingActivity.class);
                                intent.putExtra("account",account);
                                intent.putExtra("flag",1);
                                PrepayActivity.this.startActivity(intent);
                            }
                        }).execute(map);
                    }
                })
                .create(com.qmuiteam.qmui.R.style.QMUI_Dialog).show();
    }

}
